import TodoItem from './components/TodoItem';
import {useDispatch, useSelector} from 'react-redux';
import {
  deleteTodo,
  updateTodoState,
  Todo,
  optimisticUpdateTodoState,
} from './todoSlice';
import {View, FlatList} from 'react-native';

import {RootState, AppDispatch} from '../../app/store';
import TodoListSeparator from './components/TodoListSeparator';
import TodoListFooter from './components/TodoListFooter';
import TodoListEmpty from './components/TodoListEmpty';
export const TodoListByState = ({
  state,
}: {
  state: 'todo' | 'pending' | 'done';
}) => {
  const dispatch = useDispatch<AppDispatch>();
  const todos = useSelector((rootState: RootState) =>
    rootState.todos.items.filter(todo => todo.state === state),
  );
  console.log('todos', todos);

  const handleDelete = (id: string) => {
    dispatch(deleteTodo(id));
  };

  const handleToggleState = (todo: Todo) => {
    const nextState =
      todo.state === 'todo'
        ? 'pending'
        : todo.state === 'pending'
        ? 'done'
        : 'todo';
    dispatch(optimisticUpdateTodoState({id: todo._id, state: nextState})); // 先更新本地

    dispatch(updateTodoState({id: todo._id, state: nextState}));
  };

  return (
    <View className="mb-5">
      <FlatList
        data={todos}
        keyExtractor={item => item.startTime.toString()}
        ItemSeparatorComponent={TodoListSeparator}
        renderItem={({item}) => (
          <TodoItem
            todo={item}
            onDelete={() => handleDelete(item._id)}
            onToggleState={() => handleToggleState(item)}
          />
        )}
        ListFooterComponent={TodoListFooter}
        ListEmptyComponent={TodoListEmpty}
      />
    </View>
  );
};
// 导出为独立组件用于导航
export const TodoTab = () => <TodoListByState state="todo" />;
export const PendingTab = () => <TodoListByState state="pending" />;
export const DoneTab = () => <TodoListByState state="done" />;
